﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ScooterLand
{
    public partial class OrderForm : Form
    {
        private int clientID; // private variable
        private int orderID; // private variable

        Backend.Program controller = new Backend.Program(); // connect to backend code

        public OrderForm(int cid = 0, int oid = 0) // load with optional parameter
        {
            InitializeComponent();
            clientID = cid; // set clientID equal to input paramenter
            orderID = oid; // set orderID equal to input paramenter
        }

        private void orderItem_Click(object sender, EventArgs e)
        {
            OrderForm oForm = new OrderForm();
            oForm.Show();
            this.Close();
        }

        private void customersItem_Click(object sender, EventArgs e)
        {
            CustomerForm cForm = new CustomerForm();
            cForm.Show();
            this.Close();
        }

        private void productsItem_Click(object sender, EventArgs e)
        {
            ProductForm pForm = new ProductForm();
            pForm.Show();
            this.Close();
        }

        private void employeesItem_Click(object sender, EventArgs e)
        {
            EmployeeForm eForm = new EmployeeForm();
            eForm.Show();
            this.Close();
        }

        private void invoicesItem_Click(object sender, EventArgs e)
        {
            InvoiceForm iForm = new InvoiceForm();
            iForm.Show();
            this.Close();
        }

        private void exitItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OrderForm_Load(object sender, EventArgs e)
        {
            if (clientID != 0 && orderID != 0)
            {
                string[] orderArray = controller.GetOrderInfo(orderID);
                txtTotalPrice.Text = orderArray[1];
                string status = orderArray[3];
                int employeeID = Convert.ToInt32(orderArray[2]);

                // loads employees
                DataTable employeeTable = controller.ListEmployees();

                cmbSearchMechanic.DataSource = employeeTable;
                cmbSearchMechanic.DisplayMember = "fullname";
                cmbSearchMechanic.ValueMember = "eid";

                cmbSearchMechanic.SelectedValue = 0;
                cmbSearchMechanic.SelectedText = "-- Vælg mekaniker --";

                cmbMechanic.DataSource = employeeTable;
                cmbMechanic.DisplayMember = "fullname";
                cmbMechanic.ValueMember = "eid";

                // Define default values
                if (employeeID != 0)
                {
                    string[] employeeArray = controller.GetEmployeeInfo(employeeID);

                    cmbMechanic.SelectedValue = employeeID;
                }
                else
                {
                    cmbMechanic.SelectedValue = 0;
                    cmbMechanic.SelectedText = "-- Vælg mekaniker --";
                }

                // loads status
                DataTable statusTable = new DataTable("statusTable");
                statusTable.Columns.Add("id");
                statusTable.Columns.Add("name");

                statusTable.Rows.Add("pending", "Afventer");
                statusTable.Rows.Add("inprogress", "Igangværende");
                statusTable.Rows.Add("completed", "Afsluttet");

                cmbStatus.DataSource = statusTable;
                cmbStatus.DisplayMember = "name";
                cmbStatus.ValueMember = "id";

                // Define default values
                if (orderArray[3] == "pending")
                    cmbStatus.SelectedValue = "pending";
                else if (orderArray[3] == "inprogress")
                    cmbStatus.SelectedValue = "inprogress";
                else if (orderArray[3] == "completed")
                    cmbStatus.SelectedValue = "completed";

                // SMS notification
                if (orderArray[4] == "yes")
                    cbSMS.Checked = true;
                else
                    cbSMS.Checked = false;

                // load customer info
                string[] clientArray = controller.GetCustomerInfo(clientID);
                txtClientID.Text = clientArray[0];
                txtFullName.Text = clientArray[1];
                txtAddress.Text = clientArray[2];
                txtZipcode.Text = clientArray[3];
                txtTelephone.Text = clientArray[4];
                txtEmail.Text = clientArray[5];
                txtCity.Text = clientArray[6];
                txtEmployee.Text = clientArray[7];

                // Load customers scooters
                DataTable scooterTable = controller.FindScooters(clientID);
                DataRow[] scooterRows = scooterTable.Select();

                foreach (DataRow row in scooterRows)
                {
                    string brandID = row["bid"].ToString();
                    string scooterBrand = controller.FindBrand(brandID);
                    string[] strScooter = { scooterBrand, row["registration"].ToString(), row["vin"].ToString() };
                    ListViewItem lvScooter = new ListViewItem(strScooter);
                    lvScooters.Items.Add(lvScooter);
                }

                // load scooters added to order
                DataTable selectedTable = controller.OrderScooterList(orderID);
                DataRow[] selectedRows = selectedTable.Select();

                foreach (DataRow row in selectedRows)
                {
                    string brandID = row[0].ToString();
                    string scooterBrand = controller.FindBrand(brandID);

                    string[] str = { scooterBrand, row[2].ToString(), row[1].ToString() };
                    ListViewItem lvItem = new ListViewItem(str);
                    lvSelectedScooters.Items.Add(lvItem);

                    // remove selected scooters from listview
                    lvScooters.Items.Remove(lvScooters.FindItemWithText(row[1].ToString()));
                }

                // loads product groups
                DataTable groupTable = controller.ListGroups();

                cmbGroup.DataSource = groupTable;
                cmbGroup.DisplayMember = "1";
                cmbGroup.ValueMember = "0";

                // Define default values
                cmbGroup.SelectedValue = 0;
                cmbGroup.SelectedText = "-- Vælg varegruppe --";

                // load products added to order
                DataTable pSelectedTable = controller.GetOrderlines(orderID);
                DataRow[] pSelectedRows = pSelectedTable.Select();

                foreach (DataRow row in pSelectedRows)
                {
                    string[] str = { row[0].ToString(), row[3].ToString(), row[4].ToString(), row[1].ToString(), row[2].ToString() };
                    ListViewItem lvItem = new ListViewItem(str);
                    lvSelectedProducts.Items.Add(lvItem);
                }
            }
            else if (clientID != 0 && orderID == 0)
            {
                string[] clientArray = controller.GetCustomerInfo(clientID);
                txtClientID.Text = clientArray[0];
                txtFullName.Text = clientArray[1];
                txtAddress.Text = clientArray[2];
                txtZipcode.Text = clientArray[3];
                txtTelephone.Text = clientArray[4];
                txtEmail.Text = clientArray[5];
                txtCity.Text = clientArray[6];
                txtEmployee.Text = clientArray[7];

                bool result;
                string currentDate = DateTime.Today.Date.ToString("d");
                controller.CreateOrder(clientID, 0, currentDate, out result, out orderID);

                if (result != true)
                    MessageBox.Show("Ordren kunne ikke oprettes.");
                else
                {
                    // loads employees
                    DataTable employeeTable = controller.ListEmployees();

                    cmbSearchMechanic.DataSource = employeeTable;
                    cmbSearchMechanic.DisplayMember = "fullname";
                    cmbSearchMechanic.ValueMember = "eid";

                    cmbSearchMechanic.SelectedValue = 0;
                    cmbSearchMechanic.SelectedText = "-- Vælg mekaniker --";

                    cmbMechanic.DataSource = employeeTable;
                    cmbMechanic.DisplayMember = "fullname";
                    cmbMechanic.ValueMember = "eid";

                    // Define default values
                    cmbMechanic.SelectedValue = 0;
                    cmbMechanic.SelectedText = "-- Vælg mekaniker --";

                    // Load customers scooters
                    DataTable scooterTable = controller.FindScooters(clientID);
                    DataRow[] scooterRows = scooterTable.Select();

                    foreach (DataRow row in scooterRows)
                    {
                        string brandID = row["bid"].ToString();
                        string scooterBrand = controller.FindBrand(brandID);
                        string[] strScooter = { scooterBrand, row["registration"].ToString(), row["vin"].ToString() };
                        ListViewItem lvScooter = new ListViewItem(strScooter);
                        lvScooters.Items.Add(lvScooter);
                    }

                    // loads product groups
                    DataTable groupTable = controller.ListGroups();

                    cmbGroup.DataSource = groupTable;
                    cmbGroup.DisplayMember = "1";
                    cmbGroup.ValueMember = "0";

                    // Define default values
                    cmbGroup.SelectedValue = 0;
                    cmbGroup.SelectedText = "-- Vælg varegruppe --";

                    string[] orderArray = controller.GetOrderInfo(orderID);
                    // loads status
                    DataTable statusTable = new DataTable("statusTable");
                    statusTable.Columns.Add("id");
                    statusTable.Columns.Add("name");

                    statusTable.Rows.Add("pending", "Afventer");
                    statusTable.Rows.Add("inprogress", "Igangværende");
                    statusTable.Rows.Add("completed", "Afsluttet");

                    cmbStatus.DataSource = statusTable;
                    cmbStatus.DisplayMember = "name";
                    cmbStatus.ValueMember = "id";

                    // Define default values
                    if (orderArray[3] == "pending")
                        cmbStatus.SelectedValue = "pending";
                    else if (orderArray[3] == "inprogress")
                        cmbStatus.SelectedValue = "inprogress";
                    else if (orderArray[3] == "completed")
                        cmbStatus.SelectedValue = "completed";
                }
            }
            else
            {
                DataTable employeeTable = controller.ListEmployees();

                cmbSearchMechanic.DataSource = employeeTable;
                cmbSearchMechanic.DisplayMember = "fullname";
                cmbSearchMechanic.ValueMember = "eid";

                cmbSearchMechanic.SelectedValue = 0;
                cmbSearchMechanic.SelectedText = "-- Vælg mekaniker --";
            }
        }

        private void btnScooterAdd_Click(object sender, EventArgs e)
        {
            string addScooterBrand = lvScooters.SelectedItems[0].SubItems[0].Text;
            string addScooterReg = lvScooters.SelectedItems[0].SubItems[1].Text;
            string addScooterVIN = lvScooters.SelectedItems[0].SubItems[2].Text;
            bool result = controller.OrderScooterAdd(orderID, addScooterVIN);

            if (result != true)
                MessageBox.Show("Handlingen kunne ikke gennemføres");
            else
            {
                string[] str = { addScooterBrand.ToString(), addScooterReg, addScooterVIN };
                ListViewItem lvItem = new ListViewItem(str);
                lvSelectedScooters.Items.Add(lvItem);

                lvScooters.Items.Remove(lvScooters.FindItemWithText(lvScooters.SelectedItems[0].SubItems[2].Text));
            }
        }

        private void btnScooterRemove_Click(object sender, EventArgs e)
        {
            string removeScooterBrand = lvSelectedScooters.SelectedItems[0].SubItems[0].Text;
            string removeScooterReg = lvSelectedScooters.SelectedItems[0].SubItems[1].Text;
            string removeScooterVIN = lvSelectedScooters.SelectedItems[0].SubItems[2].Text;
            bool result = controller.OrderScooterRemove(orderID, removeScooterVIN);

            if (result != true)
                MessageBox.Show("Handlingen kunne ikke gennemføres");
            else
            {
                string[] str = { removeScooterBrand.ToString(), removeScooterReg, removeScooterVIN };
                ListViewItem lvItem = new ListViewItem(str);
                lvScooters.Items.Add(lvItem);

                lvSelectedScooters.Items.Remove(lvSelectedScooters.FindItemWithText(lvSelectedScooters.SelectedItems[0].SubItems[2].Text));
            }
        }

        private void btnOrderSearch_Click(object sender, EventArgs e)
        {
            lvOrders.Items.Clear();
            int employeeID = Convert.ToInt32(cmbSearchMechanic.SelectedValue);

            DataTable resultTable = controller.FindOrders(txtSearchTelephone.Text, txtSearchName.Text, employeeID);
            DataRow[] resultRows = resultTable.Select();

            foreach (DataRow row in resultRows)
            {
                string[] customerInfo = controller.GetCustomerInfo(Convert.ToInt32(row[2]));
                string[] employeeInfo = controller.GetEmployeeInfo(Convert.ToInt32(row[3]));

                string customerName = customerInfo[1];
                string employeeName = employeeInfo[1];

                string[] str = { row[0].ToString(), row[1].ToString(), customerName, employeeName, row[4].ToString() };
                ListViewItem lvItem = new ListViewItem(str);
                lvOrders.Items.Add(lvItem);
            }

            // loads product groups
            DataTable groupTable = controller.ListGroups();

            cmbGroup.DataSource = groupTable;
            cmbGroup.DisplayMember = "1";
            cmbGroup.ValueMember = "0";

            // Define default values
            cmbGroup.SelectedValue = 0;
            cmbGroup.SelectedText = "-- Vælg varegruppe --";
        }

        private void btnSelectOrder_Click(object sender, EventArgs e)
        {
            lvScooters.Items.Clear();
            lvSelectedScooters.Items.Clear();
            lvProducts.Items.Clear();
            lvSelectedProducts.Items.Clear();

            // Set Ordre ID
            orderID = Convert.ToInt32(lvOrders.SelectedItems[0].SubItems[0].Text);

            string[] orderArray = controller.GetOrderInfo(orderID);
            txtTotalPrice.Text = orderArray[1];
            int employeeID = Convert.ToInt32(orderArray[2]);

            // loads employees
            DataTable employeeTable = controller.ListEmployees();

            cmbMechanic.DataSource = employeeTable;
            cmbMechanic.DisplayMember = "fullname";
            cmbMechanic.ValueMember = "eid";

            // Define default values
            if (employeeID != 0)
            {
                string[] employeeArray = controller.GetEmployeeInfo(employeeID);

                cmbMechanic.SelectedValue = employeeID;
            }
            else
            {
                cmbMechanic.SelectedValue = 0;
                cmbMechanic.SelectedText = "-- Vælg mekaniker --";
            }

            // loads status
            DataTable statusTable = new DataTable("statusTable");
            statusTable.Columns.Add("id");
            statusTable.Columns.Add("name");

            statusTable.Rows.Add("pending", "Afventer");
            statusTable.Rows.Add("inprogress", "Igangværende");
            statusTable.Rows.Add("completed", "Afsluttet");

            cmbStatus.DataSource = statusTable;
            cmbStatus.DisplayMember = "name";
            cmbStatus.ValueMember = "id";

            // Define default values
            if (orderArray[3] == "pending")
                cmbStatus.SelectedValue = "pending";
            else if (orderArray[3] == "inprogress")
                cmbStatus.SelectedValue = "inprogress";
            else if (orderArray[3] == "completed")
                cmbStatus.SelectedValue = "completed";

            // SMS notification
            if (orderArray[4] == "yes")
                cbSMS.Checked = true;
            else
                cbSMS.Checked = false;

            // Set Client ID
            clientID = Convert.ToInt32(orderArray[0]);

            string[] clientArray = controller.GetCustomerInfo(clientID);
            txtClientID.Text = clientArray[0];
            txtFullName.Text = clientArray[1];
            txtAddress.Text = clientArray[2];
            txtZipcode.Text = clientArray[3];
            txtTelephone.Text = clientArray[4];
            txtEmail.Text = clientArray[5];
            txtCity.Text = clientArray[6];
            txtEmployee.Text = clientArray[7];

            // Load customers scooters
            DataTable scooterTable = controller.FindScooters(clientID);
            DataRow[] scooterRows = scooterTable.Select();

            foreach (DataRow row in scooterRows)
            {
                string brandID = row["bid"].ToString();
                string scooterBrand = controller.FindBrand(brandID);
                string[] strScooter = { scooterBrand, row["registration"].ToString(), row["vin"].ToString() };
                ListViewItem lvScooter = new ListViewItem(strScooter);
                lvScooters.Items.Add(lvScooter);
            }

            // load scooters added to order
            DataTable selectedTable = controller.OrderScooterList(orderID);
            DataRow[] selectedRows = selectedTable.Select();

            foreach (DataRow row in selectedRows)
            {
                string scooterBrand = controller.FindBrand(row[0].ToString());

                string[] str = { scooterBrand, row[2].ToString(), row[1].ToString() };
                ListViewItem lvItem = new ListViewItem(str);
                lvSelectedScooters.Items.Add(lvItem);

                // remove selected scooters from listview
                lvScooters.Items.Remove(lvScooters.FindItemWithText(row[1].ToString()));
            }

            // load products added to order
            DataTable pSelectedTable = controller.GetOrderlines(orderID);
            DataRow[] pSelectedRows = pSelectedTable.Select();

            foreach (DataRow row in pSelectedRows)
            {
                string[] str = { row[0].ToString(), row[3].ToString(), row[4].ToString(), row[1].ToString(), row[2].ToString() };
                ListViewItem lvItem = new ListViewItem(str);
                lvSelectedProducts.Items.Add(lvItem);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            lvProducts.Items.Clear();
            int groupID;
            groupID = Convert.ToInt32(cmbGroup.SelectedValue);

            string searchWord = txtSearchWord.Text;

            DataTable productTable = controller.ListProducts(groupID, searchWord);
            DataRow[] productRows = productTable.Select();

            foreach (DataRow row in productRows)
            {
                string[] str = { row[0].ToString(), row[1].ToString(), row[2].ToString(), row[4].ToString() };
                ListViewItem lvItem = new ListViewItem(str);
                lvProducts.Items.Add(lvItem);
            }
        }

        private void btnProductAdd_Click(object sender, EventArgs e)
        {
            int productID, quantity;
            string price;

            productID = Convert.ToInt32(lvProducts.SelectedItems[0].SubItems[0].Text);
            quantity = Convert.ToInt32(txtQuantity.Text);

            if (txtProductPrice.Text != "0")
                price = txtProductPrice.Text;
            else
                price = lvProducts.SelectedItems[0].SubItems[2].Text;

            bool result;
            int olID;

            controller.OrderProductAdd(orderID, productID, price, quantity, out result, out olID);

            if (result != true)
                MessageBox.Show("Handlingen kunne ikke udføres.");
            else
            {
                string[] productArray = controller.GetProductInfo(productID);

                double thisPrice = Convert.ToDouble(price) * quantity;
                string subtotal = Convert.ToString(thisPrice).Replace(',', '.');

                string[] str = { olID.ToString(), productArray[0], productArray[1].Replace(',', '.'), quantity.ToString(), subtotal };
                ListViewItem lvItem = new ListViewItem(str);
                lvSelectedProducts.Items.Add(lvItem);

                txtTotalPrice.Text = Convert.ToString(Convert.ToDouble(txtTotalPrice.Text) + Convert.ToDouble(thisPrice));
            }
        }

        private void btnProductRemove_Click(object sender, EventArgs e)
        {
            int olID;
            double subtotal;
            string totalprice;

            olID = Convert.ToInt32(lvSelectedProducts.SelectedItems[0].Text);

            if (olID > 0)
            {
                string[] orderlineArray = controller.GetOrderlineInfo(olID);

                subtotal = Convert.ToDouble(orderlineArray[3]);
                totalprice = Convert.ToString(Convert.ToDouble(txtTotalPrice.Text) - subtotal);

                bool result = controller.OrderProductRemove(orderID, olID, totalprice);

                if (result != true)
                    MessageBox.Show("Handlingen kunne ikke udføres.");
                else
                {
                    lvSelectedProducts.Items.Remove(lvSelectedProducts.SelectedItems[0]);
                    txtTotalPrice.Text = totalprice;
                }
            }
            else
                MessageBox.Show("Intet produkt er valgt");
        }

        private void btnOrderSave_Click(object sender, EventArgs e)
        {
            int employeeID = Convert.ToInt32(cmbMechanic.SelectedValue);
            bool result;

            string smsnotification;
            if (cbSMS.Checked == true)
                smsnotification = "yes";
            else
                smsnotification = "no";

            string status = cmbStatus.SelectedValue.ToString();

            result = controller.UpdateOrder(orderID, employeeID, smsnotification, status);

            if (result != true)
                MessageBox.Show("Handlingen kunne ikke udføres.");
        }
    }
}
